// 实现这个项目的构建任务
const {src, dest, parallel, series, watch} = require('gulp')
const del = require('del')
const browserSync = require('browser-sync')
const bs = browserSync.create()
const plugins = require('gulp-load-plugins') //在webstorm中，plugins.sass不规范，有语法错误导致报错，所以我就没用
const sass = require('gulp-sass')(require('sass'));
const babel = require('gulp-babel')
const swig = require('gulp-swig')
const imagemin = require('gulp-imagemin')
const useref = require('gulp-useref')
const uglify = require('gulp-uglify')
const cleanCss = require('gulp-clean-css')
const htmlMin = require('gulp-htmlmin')
const gulpIf = require('gulp-if')
const clean = () => { // 清除 dist文件
  return del(['dist','temp'])
}
const style = () => { // 样式编译
  return src('src/assets/styles/*.scss',{base:'src'})
    .pipe(sass({outputStyle:'expanded'}))
    .pipe(dest('temp'))
    .pipe(bs.reload({stream:true}))
}
const script = () => { // 脚本编译
  return src('src/assets/scripts/*.js',{base:'src'})
    .pipe(babel({presets:['@babel/preset-env']}))
    .pipe(dest('temp'))
    .pipe(bs.reload({stream:true}))
}
const page = () => { // 页面模版编译
  return src('src/**/*.html',{base:'src'}) // 这里已经写 **/*.html了但为什么layouts和partials打包不进去呢？
    .pipe(swig())
    .pipe(dest('temp'))
    .pipe(bs.reload({stream:true}))
}
const image = () => { // 图片压缩
  return src('src/assets/images/**',{base:'src'})
    .pipe(imagemin())
    .pipe(dest('dist'))
}
const font = () => { // 字体文件压缩
  return src('src/assets/fonts/**',{base:'src'})
    .pipe(imagemin())
    .pipe(dest('dist'))
}
const extra = () => { // 其他的文件例如public
  return src('public/**',{base:'public'})
    .pipe(dest('dist'))
}
const gulpUseRef = () => {
  return src('temp/*.html', {base:'temp'})
    .pipe(useref({searchPath:['temp','.']})) // 找根目录，使用的更多的放前面
    // 这个管道中会有三种文件 html js css
    .pipe(gulpIf(/\.js$/,uglify()))
    .pipe(gulpIf(/\.css$/,cleanCss()))
    .pipe(gulpIf(/\.html$/,htmlMin({collapseWhitepace:true,minifyCSS:true,minifyJS: true})))
    .pipe(dest('dist'))
}
const serve = () => {
  watch('src/assets/styles/*.scss', style)
  watch('src/assets/scripts/*.js', script)
  watch('src/**/*.html', page)
  watch(
    [
      'src/assets/images/**',
      'src/assets/fonts/**',
      'public/**'
    ],
    bs.reload
  )

  bs.init({
    notify:false,
    port:2080,
    server:{
      baseDir:['temp', 'src', 'public'], // 优化，开发的过程中不要打包静态文件(图片、字体、其他文件) // 变成数组后会先到第一个里面找找不到再一个个向后面的里面找
      routes:{
        '/node_modules':'node_modules'
      }
    }
  })
}
const compile = parallel(style, script, page)
// 上线之前执行的任务
const build = series(
  clean,
  parallel(
    series(compile,gulpUseRef),
    image,
    font,
    extra
  )
)
const develop = series(compile,serve)
module.exports = {
  clean,
  build,
  develop,
}
